const _ = require('lodash');
const async = require('async');
const services = require('../../services');
const enums = require('../../enums');
const loopbackContext = require('loopback-context');

const commonService = services.common;
const eLancoService = services.eLanco;

module.exports = (req, res, callback) => {
  const { WfRunInstance: formDetailModel, WfRunFlowDetail: approvalDetailModel } = commonService.getModels();
  const data = req.body;
  const formId = req.body.formId;
  const id = req.params.id;
  const context = loopbackContext.getCurrentContext();
  if (!_.isEmpty(data.owner)) {
    context.set('employeeId', data.owner.employeeId);
  }
  const getFormDetail = (next) => {
    eLancoService.getFormDetailIncludeAll(formId, id, next);
  };
  const copyFormDetail = (formDetail, next) => {
    formDetailModel.upsert(_.assign(formDetail, { id: null, formStatus: enums.formStatus.saved }), next);
  };
  const cancelFormDatailAfter = (formDetail, next) => {
    const form = context.get('form');
    const flow = context.get('flow');
    const returnform = context.get('returnform');
    const isCancel = returnform == 'return' ? 'return' : true;
    const approvalList = formDetail.approvalList();
    if (flow.flowRun.isEmailSend) eLancoService.handlEmailSendEvent(form, flow, formDetail, approvalList, isCancel);
    next(null, 123);
  };
  const deleteFormDetail = (data, next) => {
    formDetailModel.upsert({ id, deleted: true }, next);
  };
  const deleteApprovalList = (formDetail, next) => {
    approvalDetailModel.updateAll({ instanceId: id }, { deleted: true }, next);
  };
  async.waterfall([getFormDetail, copyFormDetail, cancelFormDatailAfter, deleteFormDetail, deleteApprovalList], callback);
};
